package com.qmds.deviceserver.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmds.common.core.entity.Device;
import com.qmds.common.core.page.PageVO;
import com.qmds.common.core.params.FileParam;
import com.qmds.common.core.utils.CodeGeneratorUtils;
import com.qmds.common.core.utils.DateUtils;
import com.qmds.common.core.utils.FilesWriterUtils;
import com.qmds.common.core.vo.R;
import com.qmds.deviceserver.device.dao.DeviceMapper;
import com.qmds.deviceserver.device.param.DeviceAddParam;
import com.qmds.deviceserver.device.param.DeviceEditParam;
import com.qmds.deviceserver.device.param.DevicePageParam;
import com.qmds.deviceserver.device.service.DeviceService;
import com.qmds.deviceserver.device.vo.DevicePageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * --- 代码敲烂 月薪过万 ---
 *
 * @author ShiJiaWei
 * @date 2024/9/7
 * @desc:
 */
@Service
public class DeviceServiceImpl implements DeviceService {

    @Resource
    private DeviceMapper deviceMapper;

    @Override
    public R<PageVO<DevicePageVO>> devicePage(DevicePageParam pageParam) {
        Page<DevicePageVO> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
        QueryWrapper<DevicePageVO> wrapper = getDevicePageVOQueryWrapper(pageParam);
        page = deviceMapper.selectDeviceOfPage(page, wrapper);

        PageVO<DevicePageVO> pageVO = new PageVO<>();
        pageVO.setTotal(page.getTotal());
        pageVO.setCurrentPage(page.getCurrent());
        List<DevicePageVO> records = page.getRecords();
        pageVO.setDataList(records);

        return R.ok("分页查询成功", pageVO);
    }

    @Override
    public R<Integer> addDevice(DeviceAddParam addParam) {
        if (addParam == null) {
            return R.fail("参数有误");
        }
        Device device = new Device();


        BeanUtils.copyProperties(addParam, device);
        device.setDeviceNo(CodeGeneratorUtils.generateCode(1,11, false));
        if (deviceMapper.insert(device) > 0) {
            try {
            FileParam fileParam = new FileParam();
            FilesWriterUtils filesWriterUtils = new FilesWriterUtils();
            fileParam.setFilePath("D:\\qmds\\deviceMsg\\");
            String fileName = device.getDeviceNo().concat("-").concat(device.getDeviceName().concat(".doc"));
            fileParam.setFileName(fileName);
            // 插入文件内容为，当前时间拼接状态状态
            String content = DateUtils.formatDate( LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss") + "设备编号：" + device.getDeviceNo() + "\n设备名称：" + device.getDeviceName() + "\n设备状态：" + "设备已禁用";
            if(device.getStatus().equals(0)){
                fileParam.setContent( content + "设备已禁用");
            }else if(device.getStatus().equals(0)){
                fileParam.setContent(content + "设备已启用");
            }else{
                fileParam.setContent(content + "设备已停用");
            }
                filesWriterUtils.createFile(fileParam);
            } catch (IOException e) {
                throw new RuntimeException("文件添加失败");
            }


            return R.ok();
        }
        return R.fail();
    }

    @Override
    public R<Integer> updateDevice(DeviceEditParam editParam) {
        if (editParam == null) {
            return R.fail("参数有误");
        }

        int updated = deviceMapper.update(new LambdaUpdateWrapper<Device>()
                .set(Device::getStatus, editParam.getStatus())
                .eq(Device::getId, editParam.getId()));
        if (updated > 0) {
            return R.ok();
        }
        return R.fail();
    }

    @Override
    public R<List<Map<String, Object>>> findStatusForCharts(Integer tid) {
        List<Map<String, Object>> statusForCharts = deviceMapper.findStatusForCharts(tid);
        List<Map<String, Object>> list = new ArrayList<>();
        AtomicLong total = new AtomicLong(0L);

        statusForCharts.forEach(item -> {
            Integer status = (Integer) item.get("status");
            Object num = item.get("count");

            Map<String, Object> maps= new HashMap<>();
            if (status == 1) {
                maps.put("name", "在线设备");
                maps.put("value", num);
                total.addAndGet((Long) num);
            } else if (status == 2){
                maps.put("name", "离线设备");
                maps.put("value", num);
                total.addAndGet((Long) num);
            }else if (status == 0) {
                maps.put("name", "禁用设备");
                maps.put("value", num);
                total.addAndGet((Long) num);
            }

            list.add(maps);
        });

        list.add(0, new HashMap<String, Object>(){
            {
                put("name", "所有设备");
                put("value", total);
            }
        });

        return R.ok(list);
    }

    /**
     * 获取查询条件
     * @param pageParam
     * @return
     */
    private QueryWrapper<DevicePageVO> getDevicePageVOQueryWrapper(DevicePageParam pageParam) {
        QueryWrapper<DevicePageVO> wrapper = new QueryWrapper<>();

        if (pageParam.getTid() != null && pageParam.getTid() > 0) {
            wrapper.eq("d.tid", pageParam.getTid());
        }

        if (pageParam.getTypeName() != null && !pageParam.getTypeName().isEmpty()) {
            wrapper.like("dt.type_name", pageParam.getTypeName());
        }

        if (pageParam.getDeviceName() != null && !pageParam.getDeviceName().isEmpty()) {
            wrapper.like("d.device_name", pageParam.getDeviceName());
        }

        if (pageParam.getDeviceNo() != null && !pageParam.getDeviceNo().isEmpty()) {
            wrapper.eq("d.device_no", pageParam.getDeviceNo());
        }

        if (pageParam.getDeviceMaker() != null && !pageParam.getDeviceMaker().isEmpty()) {
            wrapper.like("d.device_maker", pageParam.getDeviceMaker());
        }

        if (pageParam.getNodeType() != null && !pageParam.getNodeType().isEmpty()) {
            wrapper.like("d.node_type", pageParam.getNodeType());
        }

        if (pageParam.getCompany() != null && !pageParam.getCompany().isEmpty()) {
            wrapper.like("d.company", pageParam.getCompany());
        }

        if (pageParam.getStatusList() != null && !pageParam.getStatusList().isEmpty()) {
            wrapper.in("d.status", pageParam.getStatusList());
        }

        return wrapper;
    }
}
